package com.baseproject.tangram;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;

import com.baseproject.imageload.ImageLoaderUtil;
import com.tmall.wireless.tangram.TangramBuilder;
import com.tmall.wireless.tangram.TangramEngine;
import com.tmall.wireless.tangram.util.IInnerImageSetter;

/**
 * Created by hp on 2017/7/3.
 */

public class TangramHelper {

    protected TangramEngine engine;
    protected TangramBuilder.InnerBuilder builder;
    RecyclerView recyclerView;

    public TangramHelper initTangram(Context context, ITangramContainer iTangramContainer) {
        //Step 1: init tangram
        TangramBuilder.init(context, new IInnerImageSetter() {
            @Override
            public <IMAGE extends ImageView> void doLoadImageUrl(@NonNull IMAGE view,
                                                                 @Nullable String url) {
                ImageLoaderUtil.getInstance().with(context).load(url).into(view);
            }
        }, ImageView.class);

        //Step 2: register build=in cells and cards
        builder = TangramBuilder.newInnerBuilder(iTangramContainer.getActivity());
        //Step 3: register business cells and cards
        iTangramContainer.registerCellOrCard(builder);
        //Step 4: new engine
        engine = builder.build();


        iTangramContainer.addSupportAndRegisterService(engine);
        //Step 5: add card load support if you have card that drawable_loading_anim cells async
//        engine.addCardLoadSupport();
//        engine.addSimpleClickSupport(new SampleClickSupport());


        //Step 6: enable auto load more if your page's data is lazy loaded
        engine.enableAutoLoadMore(true);
        //Step 7: bind recyclerView to engine
        recyclerView = iTangramContainer.getRecyclerView();
        engine.bindView(recyclerView);

        //Step 8: listener recyclerView onScroll event to trigger auto load more
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                engine.onScrolled();
            }
        });
        //Step 9: set an offset to fix card
        engine.getLayoutManager().setFixOffset(0, 40, 0, 0);

        engine.setPreLoadNumber(3);

        //Step 10: get tangram data and pass it to engine
        return this;
    }

    public TangramEngine getEngine() {
        return engine;
    }
}
